package com.vaadin.lab2;

import java.util.HashSet;
import java.util.Set;

import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
import com.vaadin.ui.themes.Reindeer;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
public class Lab extends Application implements ClickListener, CloseListener{

	private static final int NUM_WINDOWS_IN_ROW = 5;
	private static final int WINDOW_BASE_Y = 150;
	private static final int WINDOW_WIDTH = 200;
	private static final int WINDOW_HEIGHT = 150;

	private VerticalLayout mainLayout = new VerticalLayout();

	private Window mainWindow;

	@Override
	public void init() {

		mainWindow = new Window("Lab", mainLayout);
		setMainWindow(mainWindow);

		Button button = new Button("Add window");
		mainLayout.addComponent(button);
		button.setStyleName(Reindeer.LAYOUT_BLUE);
		button.addListener(this);
	}
	
	@Override
	public void buttonClick(ClickEvent event) {

		Window window = new Window();
		window.setWidth("100%");
		mainWindow.addWindow(window);
		window.addListener(this);
		
		Button anotherButton = new Button("Add another window");
		anotherButton.addListener(addWinListener());
		window.addComponent(anotherButton);
	}

	@Override
	public void windowClose(CloseEvent e) {
		Set<Window> wins = new HashSet<Window>(mainWindow.getChildWindows());
		for (Window window : wins) {
			
			mainWindow.removeWindow(window);
		}
	}
	
	private ClickListener addWinListener(){
		return new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				Window window = new Window();
				mainWindow.addWindow(window);
				
			}
		};
	}
	
	private static int getPositionX(int n) {
		return n % NUM_WINDOWS_IN_ROW * WINDOW_WIDTH;
	}

	private static int getPositionY(int n) {
		return n / NUM_WINDOWS_IN_ROW * WINDOW_HEIGHT + WINDOW_BASE_Y;
	}

}
